package com.item.mobile;

import static com.item.mobile.MobileUtil.checkParam;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.base.dialect.PaginationSupport;
import com.base.mobile.MobException;
import com.base.mobile.MobileInfo;
import com.base.mobile.server.annotation.Mobile;
import com.base.mobile.server.annotation.MobileMethod;
import com.base.util.StringUtil;
import com.item.dao.model.News;
import com.item.dao.model.NewsExample;
import com.item.dao.model.NewsOperation;
import com.item.dao.model.NewsOperationKey;
import com.item.dao.model.PostCommentExample;
import com.item.dao.model.Unread;
import com.item.daoEx.model.NewsEx;
import com.item.service.NewsOperationService;
import com.item.service.NewsService;
import com.item.service.UnreadService;
import com.item.util.ApiUtil;
import com.item.util.ConstantResources;
import com.mobile.api.proto.MAppIndex.MUnread;
import com.mobile.api.proto.MAppNews.MNews;
import com.mobile.api.proto.MAppNews.MNewsList;
import com.mobile.api.proto.MSystem.MRet;
import com.mobile.api.proto.MSystem.MUnreadCount;


@Component
@Mobile
public class MAppNews {
	
	@Autowired
	private NewsService newsService;
	
	@Autowired
	private NewsOperationService opService;
	
	@Autowired
	private UnreadService readService;
	
	static  Logger log = Logger.getLogger(MAppNews.class);
	
	@MobileMethod(methodno = "MGetMsgCount", isLogin = true)
	public MUnread.Builder msgCount(MobileInfo mobileInfo) throws Exception {
		MUnread.Builder ret = MUnread.newBuilder();
		Unread read = readService.selectByPrimaryKey(mobileInfo.getUserid());
		if(read != null){
			ret.setModule1(read.getModule1());
			ret.setModule2(read.getModule2());
			ret.setModule3(read.getModule3());
			ret.setModule4(read.getModule4());
		}
		return ret;
	}
	
	
	@MobileMethod(methodno = "MIndexNews",isLogin=true,isPage=false)
	public MNewsList.Builder indexNews(MobileInfo mobileInfo,Integer page,Integer limit,Integer type) throws Exception {
		if(page == null)
			page = 1;
		if(limit == null)
			limit = 5;
		MNewsList.Builder ret = MNewsList.newBuilder();
		PaginationSupport.setContext(page, limit, null);
		NewsExample nex = new NewsExample();
		//这里不取广告
		if(type == null || type == 1){
			Map<String,String> map = new HashMap<String, String>();
			map.put("userid", mobileInfo.getUserid());
			List<NewsEx> lists = newsService.selectNewsList(map);
			for(NewsEx news : lists){
				ret.addNews(fillNewsData(news));
			}
		}else{
			nex.createCriteria().andTypeEqualTo(type);
			nex.setOrderByClause("date DESC,top DESC");
			List<News> lists = newsService.selectByExample(nex);
			for(News news : lists){
				ret.addNews(fillNewsData(news));
			}
		}
		
		ret.setNext(ApiUtil.getNextPageUrl("MIndexNews", mobileInfo, PaginationSupport.getContext().getTotalCount() ,page, limit,null));
		return ret;
	}
	
	
	@MobileMethod(methodno = "MNewsPraise", isLogin = true)
	public MRet.Builder praise(MobileInfo mobileInfo,String id,Integer type) throws Exception {
		//先检查news是否存在
		News news = newsService.selectByPrimaryKey(id);
		if(news == null){
			throw new MobException("id");
		}
		NewsOperation op = getNewsOperation(mobileInfo, id, type);
		if(op == null){
			op = initNewsOperation(mobileInfo.getUserid(), id, 0, 1);
			opService.insert(op);
			news.setPraiseCount(news.getPraiseCount() + 1);
			newsService.updateByPrimaryKey(news);
		}else{
			int typeBefore = op.getPraiseType();
			op.setPraiseType(type);
			opService.updateByPrimaryKey(op);
			if(typeBefore != type){
				if(type == 1 || type == null){
					news.setPraiseCount(news.getPraiseCount() + 1);
				}else{
					news.setPraiseCount(news.getPraiseCount() - 1);
				}
			}
			newsService.updateByPrimaryKey(news);
		}
		MRet.Builder ret = MRet.newBuilder();
		ret.setCode(1);
		return ret;
	}
	
	@MobileMethod(methodno = "MNewsCollect", isLogin = true)
	public MRet.Builder collect(MobileInfo mobileInfo,String id,Integer type) throws Exception {
		//先检查news是否存在
		News news = newsService.selectByPrimaryKey(id);
		if(news == null){
			throw new MobException("id");
		}
		NewsOperation op = getNewsOperation(mobileInfo, id, type);
		if(op == null){
			op = initNewsOperation(mobileInfo.getUserid(), id, 1, 0);
			opService.insert(op);
		}else{
			op.setCollectType(type);
			opService.updateByPrimaryKey(op);
		}
		MRet.Builder ret = MRet.newBuilder();
		ret.setCode(1);
		return ret;
	}
	
	public NewsOperation getNewsOperation(MobileInfo mobileInfo,String id,Integer type)throws Exception{
		checkParam(id, "id");
		if(type == null){
			type = 1;
		}
		NewsOperationKey key = new NewsOperationKey();
		key.setPid(id);
		key.setUserid(mobileInfo.getUserid());
		NewsOperation op = opService.selectByPrimaryKey(key);
		return op;
	}
	
	public NewsOperation initNewsOperation(String userid,String pid,int collectType,int praiseType){
		NewsOperation op = new NewsOperation();
		op.setPid(pid);
		op.setUserid(userid);
		op.setCollectType(collectType);
		op.setPraiseType(praiseType);
		op.setCreateTime(new Date());
		op.setModifyTime(op.getCreateTime());
		return op;
	}
	
	public MNews.Builder fillNewsData(NewsEx news){
		MNews.Builder ret = fillNewsData((News)news);
		ret.setIsCollected(news.getIsCollect());
		ret.setIsPraised(news.getIsPraise());
		return ret;
	}
	
	public MNews.Builder fillNewsData(News news){
		MNews.Builder newsRet = MNews.newBuilder();
		newsRet.setId(news.getId());
		newsRet.setTitle(news.getTitle());
		newsRet.setDesc(StringUtil.emptyIfBlank(news.getDescription()));
		newsRet.setImg(StringUtil.emptyIfBlank(news.getImg()));
		newsRet.setType(news.getType());
		newsRet.setSource(news.getSource());
		newsRet.setTime(news.getDate());
		newsRet.setBrowseCount(news.getBrowseCount());
		newsRet.setPraiseCount(news.getPraiseCount());
		newsRet.setShowType(news.getShowType());
		if(news.getType() == 1){
			if(!news.getUrl().startsWith("http")){
				newsRet.setUrl(String.format("%s%s?newsid=%s&_t=%s", ConstantResources.OSS_OUT_WEB_URL,news.getUrl(),news.getId(),String.valueOf(System.currentTimeMillis())));
			}else{
				newsRet.setUrl(String.format("%s?newsid=%s", news.getUrl(),news.getId()));
			}
		}else if(news.getType() == 3){
			newsRet.setNoteId(news.getNoteId());
		}
		return newsRet;
	}
	
}
